package com.pmpd.activity.controller.background;

import com.dmap.base.constants.Constant;
import com.dmap.base.vo.BaseVo;
import com.pmpd.activity.bo.background.AppBo;
import com.pmpd.activity.bo.background.BgHotActivityBo;
import com.pmpd.activity.bo.background.TagBo;
import com.pmpd.activity.constants.ActivityConstant;
import com.pmpd.activity.controller.background.param.AppParam;
import com.pmpd.activity.controller.background.param.BgHotActivityParam;
import com.pmpd.activity.controller.background.param.BgHotActivityParamList;
import com.pmpd.activity.controller.background.param.BgHotActivitySelectParam;
import com.pmpd.activity.po.HotActivity;
import com.pmpd.activity.po.HotActivityTag;
import com.pmpd.activity.rpc.ActivityAdminRpc;
import com.pmpd.activity.rpc.ActivityCommonRpc;
import com.pmpd.activity.service.background.BgHotActivityService;
import com.pmpd.activity.service.background.BgHotActivityTagService;
import com.pmpd.activity.vo.background.RecordNumAndBgHotActivityVo;
import com.pmpd.activity.vo.background.TagVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;


/**
 * \* User: helei
 * \* Date: 19/05/18
 * \* Description:
 * \
 */
@Api(value = "个人数据服务系统/热门活动API", description = "个人数据服务系统/热门活动API")
@RestController
@RequestMapping(value = "/background/pmpd-activity-server/v1/activity/hotActivity")
public class BgHotActivityController {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    private BgHotActivityTagService bgHotActivityTagService;
    @Resource
    private BgHotActivityService bgHotActivityService;
    @Resource
    private ActivityCommonRpc activityCommonRpc;
    @Resource
    private ActivityAdminRpc activityAdminRpc;

    @ResponseBody
    @ApiOperation(value = "insert 热门活动",
            notes = "1. 必填：标题title, app列表appParamList, " +
                    "开始时间beginTime, 结束时间endTime, companyId; " +
                    "2. 返回热门活动idList; ")
    @RequestMapping(value = "insert", method = RequestMethod.POST)
    public BaseVo insert(@RequestBody BgHotActivityParamList param) {
        BaseVo baseVo = new BaseVo();
        if (param == null || StringUtils.isBlank(param.getTitle())
                || CollectionUtils.isEmpty(param.getAppParamList()) || StringUtils.isBlank(param.getAppParamList().get(0).getAppId())
                || !StringUtils.isNumeric(param.getAppParamList().get(0).getAppId())
                || Long.valueOf(param.getAppParamList().get(0).getAppId()).equals(0L)
                || param.getBeginTime() == null || param.getBeginTime().equals(0L)
                || param.getEndTime() == null || param.getEndTime().equals(0L)
                || StringUtils.isBlank(param.getCompanyId()) || !StringUtils.isNumeric(param.getCompanyId())
                || Long.valueOf(param.getCompanyId()).equals(0L)) {
            baseVo.setCode(Constant.RESPONSE_PARAM_ERROR_CODE);
            baseVo.setMsg(Constant.RESPONSE_PARAM_ERROR_MSG);
            return baseVo;
        }
        List<String> idList = new ArrayList<>();
        //如果有多个App编号，则插入多条热门活动
        for (AppParam appParam : param.getAppParamList()) {
            BgHotActivityParam activityParam = new BgHotActivityParam(param);
            activityParam.setAppId(appParam.getAppId());
            activityParam.setProjectId(appParam.getProjectId());
            HotActivity hotActivity = bgHotActivityService.insert(activityParam);
            if (hotActivity != null) {
                idList.add(hotActivity.getId().toString());
                //如果有多个标签，则插入多条标签记录
                if (CollectionUtils.isNotEmpty(param.getTagIdList())) {
                    for (String tagId : param.getTagIdList()) {
                        if (StringUtils.isNotBlank(tagId) && StringUtils.isNumeric(tagId) && !Long.valueOf(tagId).equals(0L)) {
                            HotActivityTag hotActivityTag = new HotActivityTag();
                            hotActivityTag.setHotActivityId(hotActivity.getId());
                            hotActivityTag.setTagId(Long.valueOf(tagId));
                            bgHotActivityTagService.insert(hotActivityTag);
                        }
                    }
                }
            }
        }
        if (CollectionUtils.isEmpty(idList)) {
            baseVo.setCode(Constant.RESPONSE_INSERT_ERROR_CODE);
            baseVo.setMsg(Constant.RESPONSE_INSERT_ERROR_MSG);
            return baseVo;
        }
        baseVo.setData(idList);
        return baseVo;
    }

    @ResponseBody
    @ApiOperation(value = "修改 热门活动",
            notes = "1. 必填： id, 标题title, app列表appParamList, usable" +
                    " 开始时间beginTime, 结束时间endTime, companyId; " +
                    " editorAccount;")
    @RequestMapping(value = "update", method = RequestMethod.POST)
    public BaseVo update(@RequestBody BgHotActivityParamList param) {
        BaseVo baseVo = new BaseVo();
        if (param == null || StringUtils.isBlank(param.getId()) || !StringUtils.isNumeric(param.getId())
                || Long.valueOf(param.getId()).equals(0L)
                || StringUtils.isBlank(param.getTitle())
                || CollectionUtils.isEmpty(param.getAppParamList()) || StringUtils.isBlank(param.getAppParamList().get(0).getAppId())
                || !StringUtils.isNumeric(param.getAppParamList().get(0).getAppId())
                || Long.valueOf(param.getAppParamList().get(0).getAppId()).equals(0L)
                || param.getBeginTime() == null || param.getBeginTime().equals(0L)
                || param.getEndTime() == null || param.getEndTime().equals(0L)
                || StringUtils.isBlank(param.getCompanyId()) || !StringUtils.isNumeric(param.getCompanyId())
                || Long.valueOf(param.getCompanyId()).equals(0L)
                || param.getUsable() == null || param.getUsable().equals(0)) {
            baseVo.setCode(Constant.RESPONSE_PARAM_ERROR_CODE);
            baseVo.setMsg(Constant.RESPONSE_PARAM_ERROR_MSG);
            return baseVo;
        }
        //上架状态的热门活动不能编辑和删除
        if (param.getUsable().equals(ActivityConstant.ACTIVITY_USABLE)) {
            baseVo.setCode(ActivityConstant.RESPONSE_ACTIVITY_USABLE_ERROR_CODE);
            baseVo.setMsg(ActivityConstant.RESPONSE_ACTIVITY_USABLE_ERROR_MSG);
            return baseVo;
        }
        boolean success;
        try {
            BgHotActivityParam activityParam = new BgHotActivityParam(param);
            activityParam.setAppId(param.getAppParamList().get(0).getAppId());
            activityParam.setProjectId(param.getAppParamList().get(0).getProjectId());
            success = bgHotActivityService.update(activityParam);
        } catch (RuntimeException e) {
            logger.error(e.getMessage());
            baseVo.setCode(Constant.RESPONSE_UPDATE_ERROR_CODE);
            baseVo.setMsg(Constant.RESPONSE_UPDATE_ERROR_MSG);
            return baseVo;
        }
        if (!success) {
            baseVo.setCode(Constant.RESPONSE_UPDATE_ERROR_CODE);
            baseVo.setMsg(Constant.RESPONSE_UPDATE_ERROR_MSG);
        }
        bgHotActivityTagService.deleteByHotActivityId(Long.valueOf(param.getId()));
        //如果有多个标签，则插入多条标签记录
        if (param.getTagIdList() != null) {
            for (String tagId : param.getTagIdList()) {
                if (StringUtils.isNotBlank(tagId) && StringUtils.isNumeric(tagId) && !Long.valueOf(tagId).equals(0L)) {
                    HotActivityTag hotActivityTag = new HotActivityTag();
                    hotActivityTag.setHotActivityId(Long.valueOf(param.getId()));
                    hotActivityTag.setTagId(Long.valueOf(tagId));
                    bgHotActivityTagService.insert(hotActivityTag);
                }
            }
        }
        return baseVo;
    }

    @ResponseBody
    @ApiOperation(value = "批量删除 热门活动", notes = "1. 必填： id;")
    @RequestMapping(value = "delete/deleteByIdList", method = RequestMethod.POST)
    public BaseVo deleteByIdList(@RequestBody List<String> idList) {
        BaseVo baseVo = new BaseVo();
        if (CollectionUtils.isEmpty(idList)) {
            baseVo.setCode(Constant.RESPONSE_PARAM_ERROR_CODE);
            baseVo.setMsg(Constant.RESPONSE_PARAM_ERROR_MSG);
            return baseVo;
        }
        List<Long> deleteIdList = new ArrayList<>();
        //上架状态的热门活动不能编辑和删除, 只要有一个不符合，则整个删除操作要回滚
        for (String id : idList) {
            if (StringUtils.isNotBlank(id) && StringUtils.isNumeric(id) && !Long.valueOf(id).equals(0L)) {
                HotActivity hotActivity = bgHotActivityService.selectById(Long.valueOf(id));
                if (hotActivity != null && hotActivity.getUsable() != null
                        && hotActivity.getUsable().equals(ActivityConstant.ACTIVITY_USABLE)) {
                    baseVo.setCode(ActivityConstant.RESPONSE_ACTIVITY_USABLE_ERROR_CODE);
                    baseVo.setMsg(ActivityConstant.RESPONSE_ACTIVITY_USABLE_ERROR_MSG);
                    return baseVo;
                }
                deleteIdList.add(Long.valueOf(id));
            } else {
                baseVo.setCode(Constant.RESPONSE_PARAM_ERROR_CODE);
                baseVo.setMsg(Constant.RESPONSE_PARAM_ERROR_MSG);
                return baseVo;
            }
        }
        boolean success = bgHotActivityService.deleteByIdList(deleteIdList);
        if (!success) {
            baseVo.setCode(Constant.RESPONSE_DELETE_ERROR_CODE);
            baseVo.setMsg(Constant.RESPONSE_DELETE_ERROR_MSG);
        }
        bgHotActivityTagService.deleteByHotActivityIdList(deleteIdList);
        return baseVo;
    }

    @ResponseBody
    @ApiOperation(value = "根据id 查询热门活动", notes = "1. 必填： id;")
    @RequestMapping(value = "select/selectById", method = RequestMethod.GET)
    public BaseVo selectById(@RequestParam String id) {
        BaseVo baseVo = new BaseVo();
        if (StringUtils.isBlank(id) || !StringUtils.isNumeric(id) || Long.valueOf(id).equals(0L)) {
            baseVo.setCode(Constant.RESPONSE_PARAM_ERROR_CODE);
            baseVo.setMsg(Constant.RESPONSE_PARAM_ERROR_MSG);
            return baseVo;
        }
        HotActivity hotActivity = bgHotActivityService.selectById(Long.valueOf(id));
        BgHotActivityBo bo = null;
        if (hotActivity != null) {
            bo = new BgHotActivityBo(hotActivity);
            //获得app名称
            AppBo appBo = activityAdminRpc.selectAppById(bo.getAppId());
            if (appBo != null) {
                bo.setProjectName(appBo.getProjectName());
            }
            List<TagVo> tagVoList = new ArrayList<>();
            List<HotActivityTag> hotActivityTagList = bgHotActivityTagService.selectByHotActivityId(Long.valueOf(id));
            if (CollectionUtils.isNotEmpty(hotActivityTagList)) {
                //获得标签列表
                for (HotActivityTag hotActivityTag : hotActivityTagList) {
                    TagBo tagBo = activityCommonRpc.selectTagById(hotActivityTag.getTagId().toString());
                    if (tagBo != null) {
                        tagVoList.add(new TagVo(tagBo));
                    }
                }
            }
            bo.setTagVoList(tagVoList);
            Integer hotActivityStatus = bgHotActivityService.getHotActivityStatus(hotActivity);
            bo.setHotActivityStatus(hotActivityStatus);
        }
        List<BgHotActivityBo> boList = new ArrayList<>();
        boList.add(bo);
        RecordNumAndBgHotActivityVo returnVo = new RecordNumAndBgHotActivityVo(1, boList);
        baseVo.setData(returnVo);
        return baseVo;
    }

    @ResponseBody
    @ApiOperation(value = "根据参数查询 热门活动，和模糊查询、排序是一个接口",
            notes = "1. 必填：pageIndex(>=1), pageSize(>=1); " +
                    "2. 返回 热门活动 列表; ")
    @RequestMapping(value = "select/selectByExample", method = RequestMethod.POST)
    public BaseVo selectByExample(@RequestBody BgHotActivitySelectParam param) {
        BaseVo baseVo = new BaseVo();
        if (param == null || param.getPageIndex() == null || param.getPageSize() == null
                || param.getPageIndex() < 1 || param.getPageSize() < 1) {
            baseVo.setCode(Constant.RESPONSE_PARAM_ERROR_CODE);
            baseVo.setMsg(Constant.RESPONSE_PARAM_ERROR_MSG);
            return baseVo;
        }
        int recordNum = bgHotActivityService.countByBgHotActivitySelectParam(param);
        List<BgHotActivityBo> boList = new ArrayList<>();
        if (recordNum > 0) {
            List<HotActivity> list = bgHotActivityService.selectByBgHotActivitySelectParam(param);
            for (HotActivity hotActivity : list) {
                BgHotActivityBo bo = null;
                if (hotActivity != null) {
                    bo = new BgHotActivityBo(hotActivity);
                    //获得app名称
                    AppBo appBo = activityAdminRpc.selectAppById(bo.getAppId());
                    if (appBo != null) {
                        bo.setProjectName(appBo.getProjectName());
                    }
                    List<TagVo> tagVoList = new ArrayList<>();
                    List<HotActivityTag> hotActivityTagList = bgHotActivityTagService.selectByHotActivityId(hotActivity.getId());
                    if (CollectionUtils.isNotEmpty(hotActivityTagList)) {
                        //获得标签列表
                        for (HotActivityTag hotActivityTag : hotActivityTagList) {
                            TagBo tagBo = activityCommonRpc.selectTagById(hotActivityTag.getTagId().toString());
                            if (tagBo != null) {
                                tagVoList.add(new TagVo(tagBo));
                            }
                        }
                    }
                    bo.setTagVoList(tagVoList);
                    Integer hotActivityStatus = bgHotActivityService.getHotActivityStatus(hotActivity);
                    bo.setHotActivityStatus(hotActivityStatus);
                    boList.add(bo);
                }
            }
        }
        RecordNumAndBgHotActivityVo returnVo = new RecordNumAndBgHotActivityVo(recordNum, boList);
        baseVo.setData(returnVo);
        return baseVo;
    }

}    